package com.xukun.changgou.auth.handler;

import com.xukun.changgou.auth.feign.sys.SysUserFeign;
import com.xukun.changgou.common.constants.CommonConstant;
import com.xukun.changgou.common.redis.RedisUtil;
import com.xukun.changgou.common.response.ResponseEnum;
import com.xukun.changgou.common.utils.HttpUtil;
import com.xukun.changgou.common.utils.JwtUtil;
import com.xukun.changgou.service.api.sys.enums.UserOnlineEnum;
import com.xukun.changgou.service.api.sys.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author xukun
 * @Date 2021-06-03 16:35
 * @Description 登出成功处理器
 */
@Component
public class BaseLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysUserFeign userFeign;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取token
        String token = request.getHeader(CommonConstant.TOKEN_HEADER);
        try {
            String subject = JwtUtil.getSubject(token);
            String[] split = subject.split("\\|");
            Integer userId = Integer.valueOf(split[0]);
            String username = split[1];
            userFeign.update(new UserModel().setId(userId).setOnlineFlag(UserOnlineEnum.getValue(UserOnlineEnum.下线)));
            //清空redis中的权限数据
            redisUtil.delete(username + CommonConstant.REDIS_USER_AUTH_SUFFIX);
            //将该token放入token黑名单中,同时加入一个过期时间，方便定时任务清理
            long expireTime = System.currentTimeMillis() + CommonConstant.TOKEN_TTL;
            redisUtil.lLeftPush(CommonConstant.REDIS_TOKEN_BLACK_LIST, token + "|" + expireTime);
        } catch (Exception e) {
            throw e;
        }
        HttpUtil.doReturn(response, true, ResponseEnum.SUCCESS);
    }
}
